<template>
  <div class="task-detail">
    <!-- 个人任务详情 -->
    <div v-if="taskData.fType === '个人任务'" class="personal-task">
      <div v-loading="loading" class="detail-content">
        <!-- 标题 -->
        <div class="detail-section">
          <div class="section-title">任务标题</div>
          <div class="section-content">{{ detailData.text || '--' }}</div>
        </div>

        <!-- 内容 -->
        <div class="detail-section" v-if="detailData.jobinfo">
          <div class="section-title">任务内容</div>
          <div class="section-content">
            {{ parseJobInfo(detailData.jobinfo) }}
          </div>
        </div>

        <div class="detail-section" v-if="detailData.jobinfo">
          <div class="section-title">反馈内容</div>
          <div class="section-content">
            {{ parseJobInfoValue(detailData.jobinfo) }}
          </div>
        </div>

        <!-- 附件信息 -->
        <div class="detail-section" v-if="attachments && attachments.length > 0">
          <div class="section-title">附件信息</div>
          <div class="section-content">
            <div class="attachment-list">
              <div
                v-for="(file, index) in attachments"
                :key="index"
                class="attachment-item"
                @click="previewFile(file)"
              >
                <el-image
                  v-if="isImage(file.url)"
                  :src="file.thumbUrl || file.url"
                  :preview-src-list="[file.url]"
                  fit="cover"
                  class="attachment-image"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
                <div v-else class="file-icon">
                  <i class="el-icon-document"></i>
                </div>
                <div class="file-name">{{ file.name }}</div>
              </div>
            </div>
          </div>
        </div>

        <!-- 时间信息 -->
        <div class="detail-section">
          <div class="section-title">其他信息</div>
          <div class="time-info">
            <div class="time-item">
              <span class="time-label">开始时间：</span>
              <span class="time-value">{{ formatDate(detailData.begindate) }}</span>
            </div>
            <div class="time-item">
              <span class="time-label">结束时间：</span>
              <span class="time-value">{{ formatDate(detailData.enddate) }}</span>
            </div>
<!--            <div class="time-item">-->
<!--              <span class="time-label">创建时间：</span>-->
<!--              <span class="time-value">{{ formatDate(detailData.creatorTime) }}</span>-->
<!--            </div>-->
            <div class="info-item">
              <span class="info-label">执行状态：</span>
              <span class="time-value" :style="detailData.executionStatus == '已完成' ? 'color: #5AC725;':'color: #F14141;'">{{ detailData.executionStatus }}</span>
            </div>
          </div>
        </div>

        <!-- 其他信息 -->
<!--        <div class="detail-section">-->
<!--          <div class="section-title">其他信息</div>-->
<!--          <div class="other-info">-->
<!--            <el-row :gutter="20">-->
<!--              <el-col :span="12">-->
<!--                <div class="info-item">-->
<!--                  <span class="info-label">任务编号：</span>-->
<!--                  <span class="info-value">{{ detailData.taskNumber || '&#45;&#45;' }}</span>-->
<!--                </div>-->
<!--              </el-col>-->
<!--              <el-col :span="12">-->
<!--                <div class="info-item">-->
<!--                  <span class="info-label">执行状态：</span>-->
<!--                  <span-->
<!--                    class="info-value status"-->
<!--                    :class="getStatusClass(detailData.executionStatus)"-->
<!--                  >-->
<!--                    {{ detailData.executionStatus || '&#45;&#45;' }}-->
<!--                  </span>-->
<!--                </div>-->
<!--              </el-col>-->
<!--              <el-col :span="12">-->
<!--                <div class="info-item">-->
<!--                  <span class="info-label">负责人：</span>-->
<!--                  <span class="info-value">{{ detailData.instantperson === 1 ? '是' : '否' }}</span>-->
<!--                </div>-->
<!--              </el-col>-->
<!--              <el-col :span="12">-->
<!--                <div class="info-item">-->
<!--                  <span class="info-label">位置信息：</span>-->
<!--                  <span class="info-value">{{ detailData.location || '&#45;&#45;' }}</span>-->
<!--                </div>-->
<!--              </el-col>-->
<!--            </el-row>-->
<!--          </div>-->
<!--        </div>-->
      </div>
    </div>

    <!-- 协同任务详情 -->
    <div v-else-if="taskData.fType === '协同任务'" class="collaborative-task">
      <div v-loading="loading" class="detail-content">
        <!-- 公共信息 -->
        <div class="detail-section" v-if="collabData.length > 0">
          <div class="section-title">任务信息</div>
          <div class="section-content">
            <div class="task-base-info">
              <div class="info-row">
                <span class="info-label">任务标题：</span>
                <span class="info-value">{{ collabData[0].text || '--' }}</span>
              </div>
              <div class="info-row" v-if="collabData[0].jobinfo">
                <span class="info-label">任务内容：</span>
                <span class="info-value">{{ parseJobInfo(collabData[0].jobinfo) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 参与人员列表 -->
        <div class="detail-section">
          <div class="section-title">参与人员</div>
          <div class="section-content">
            <div class="user-list">
              <div
                v-for="(user, index) in collabData"
                :key="index"
                class="user-item"
                :class="{ 'responsible': user.instantperson === 1 }"
              >
                <div class="user-header">
                  <div class="user-avatar">
                    {{ user.realName ? user.realName.charAt(0) : '用' }}
                  </div>
                  <div class="user-info">
                    <div class="user-name">
                      {{ user.realName || '--' }}
                      <span v-if="user.instantperson === 1" class="responsible-badge">负责人</span>
                    </div>
                    <div class="user-account">{{ user.account || '--' }}</div>
                  </div>
                  <div class="user-status">
                    <span :class="getStatusClass(user.executionStatus)">
                      {{ user.executionStatus || '--' }}
                    </span>
                  </div>
                </div>

                <!-- 个人备注 -->
                <div class="user-remark" v-if="user.remark">
                  <div class="remark-label">备注：</div>
                  <div class="remark-content">{{ user.remark }}</div>
                </div>

                <!-- 个人附件 -->
                <div class="user-attachments" v-if="userAttachments[user.id] && userAttachments[user.id].length > 0">
                  <div class="attachments-label">附件：</div>
                  <div class="attachments-list">
                    <div
                      v-for="(file, fileIndex) in userAttachments[user.id]"
                      :key="fileIndex"
                      class="attachment-mini"
                      @click="previewFile(file)"
                    >
                      <i class="el-icon-paperclip"></i>
                      <span class="file-name">{{ file.name }}</span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 底部操作按钮 -->
    <div class="detail-footer">
      <el-button @click="$emit('close')">关闭</el-button>
<!--      <el-button type="primary" @click="handleEdit">编辑</el-button>-->
    </div>
  </div>
</template>

<script>
import { getPersonalTaskDetail, getCollaborativeTaskList, getTaskAttachments } from '@/api/task'

export default {
  name: 'TaskDetail',
  props: {
    taskData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
      loading: false,
      detailData: {}, // 个人任务详情
      collabData: [], // 协同任务列表
      attachments: [], // 附件列表
      userAttachments: {} // 协同任务中每个用户的附件
    }
  },
  mounted() {
    this.loadTaskDetail()
  },
  methods: {
    // 加载任务详情
    async loadTaskDetail() {
      this.loading = true
      try {
        if (this.taskData.fType === '个人任务') {
          // 个人任务：通过fid查询详情
          const response = await getPersonalTaskDetail(this.taskData.fId)
          if (response.code === 200) {
            this.detailData = response.data
            console.log('个人任务详情:', this.detailData)
            // 解析附件
            if (this.detailData.imageurl) {
              try {
                this.attachments = JSON.parse(this.detailData.imageurl)
              } catch (e) {
                console.error('解析附件失败:', e)
                this.attachments = []
              }
            }
          } else {
            this.$message.error(response.msg || '获取任务详情失败')
          }
        } else if (this.taskData.fType === '协同任务') {
          // 协同任务：通过任务编号查询列表
          const response = await getCollaborativeTaskList(this.taskData.fTaskNumber)
          if (response.code === 200) {
            this.collabData = response.data || []
            // 为每个用户加载附件
            await this.loadUserAttachments()
          } else {
            this.$message.error(response.msg || '获取协同任务列表失败')
          }
        }
      } catch (error) {
        console.error('获取任务详情失败:', error)
        this.$message.error('获取任务详情失败')
      } finally {
        this.loading = false
      }
    },

    // 加载协同任务中每个用户的附件
    async loadUserAttachments() {
      for (const user of this.collabData) {
        try {
          const response = await getTaskAttachments(user.id)
          if (response.code === 200 && response.data.imageurl) {
            try {
              this.$set(this.userAttachments, user.id, JSON.parse(response.data.imageurl))
            } catch (e) {
              console.error(`解析用户 ${user.realName} 附件失败:`, e)
              this.$set(this.userAttachments, user.id, [])
            }
          }
        } catch (error) {
          console.error(`获取用户 ${user.realName} 附件失败:`, error)
          this.$set(this.userAttachments, user.id, [])
        }
      }
    },

    // 解析任务内容
    parseJobInfo(jobinfo) {
      try {
        const parsed = JSON.parse(jobinfo)
        // 根据示例结构提取内容
        if (parsed.option1 && parsed.option1.body) {
          return parsed.option1.body
        }
        return jobinfo
      } catch (e) {
        console.error('解析任务内容失败:', e)
        return jobinfo
      }
    },

    parseJobInfoValue(jobinfo) {
      try {
        const parsed = JSON.parse(jobinfo)
        // 根据示例结构提取内容
        if (parsed.option1 && parsed.option1.value) {
          return parsed.option1.value
        }
        return ""
      } catch (e) {
        console.error('解析任务内容失败:', e)
        return ""
      }
    },

    // 判断是否为图片
    isImage(url) {
      if (!url) return false
      const imageExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.bmp', '.webp']
      return imageExtensions.some(ext => url.toLowerCase().includes(ext))
    },

    // 预览文件
    previewFile(file) {
      if (this.isImage(file.url)) {
        // 图片预览已经在el-image中实现
        return
      }
      // 非图片文件下载
      window.open(file.url, '_blank')
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '--'
      const date = new Date(timestamp)
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}`
    },

    // 获取状态样式类
    getStatusClass(status) {
      switch (status) {
        case '已完成':
          return 'status-completed'
        case '进行中':
          return 'status-in-progress'
        case '未开始':
          return 'status-not-started'
        default:
          return 'status-unknown'
      }
    },

    // 编辑任务
    handleEdit() {
      this.$emit('edit', this.taskData.fType === '个人任务' ? this.detailData : this.collabData)
    }
  }
}
</script>

<style scoped>
.task-detail {
  max-height: 70vh;
  overflow-y: auto;
}

.detail-content {
  padding: 0 20px;
}

.detail-section {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
}

.detail-section:last-child {
  border-bottom: none;
}

.section-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin-bottom: 12px;
}

.section-content {
  color: #666;
  line-height: 1.6;
}

/* 附件样式 */
.attachment-list {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}

.attachment-item {
  width: 100px;
  text-align: center;
  cursor: pointer;
  transition: transform 0.2s;
}

.attachment-item:hover {
  transform: translateY(-2px);
}

.attachment-image {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
}

.file-icon {
  width: 80px;
  height: 80px;
  border-radius: 4px;
  border: 1px solid #e8e8e8;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  color: #409EFF;
  background: #f5f7fa;
}

.file-name {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  word-break: break-all;
}

/* 时间信息样式 */
.time-info {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.time-item {
  display: flex;
}

.time-label {
  width: 80px;
  color: #999;
}

.time-value {
  color: #333;
  flex: 1;
}

/* 其他信息样式 */
.other-info {
  padding: 12px 0;
}

.info-item {
  margin-bottom: 12px;
  display: flex;
}

.info-label {
  width: 100px;
  color: #999;
}

.info-value {
  color: #333;
  flex: 1;
}

.status {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.status-completed {
  background: #f0f9ff;
  color: #1890ff;
}

.status-in-progress {
  background: #fff7e6;
  color: #fa8c16;
}

.status-not-started {
  background: #f6ffed;
  color: #52c41a;
}

.status-unknown {
  background: #f5f5f5;
  color: #666;
}

/* 协同任务样式 */
.user-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.user-item {
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  transition: all 0.3s;
}

.user-item.responsible {
  border-color: #409EFF;
  background: #f0f9ff;
}

.user-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.user-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #409EFF;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin-right: 12px;
}

.user-info {
  flex: 1;
}

.user-name {
  font-weight: bold;
  color: #333;
  display: flex;
  align-items: center;
  gap: 8px;
}

.responsible-badge {
  background: #ff4d4f;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
}

.user-account {
  font-size: 12px;
  color: #999;
}

.user-status {
  font-size: 14px;
}

.user-remark, .user-attachments {
  margin-top: 8px;
  padding-top: 8px;
  border-top: 1px dashed #e8e8e8;
}

.remark-label, .attachments-label {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.remark-content {
  color: #666;
  line-height: 1.5;
}

.attachments-list {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.attachment-mini {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 12px;
  color: #409EFF;
  cursor: pointer;
  padding: 4px 8px;
  border-radius: 4px;
  background: #f5f7fa;
  transition: background 0.3s;
}

.attachment-mini:hover {
  background: #e6f7ff;
}

.file-name {
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 底部操作按钮 */
.detail-footer {
  padding: 20px;
  text-align: right;
  border-top: 1px solid #e8e8e8;
  margin-top: 20px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .detail-content {
    padding: 0 12px;
  }

  .attachment-item {
    width: 80px;
  }

  .attachment-image, .file-icon {
    width: 60px;
    height: 60px;
  }

  .user-header {
    flex-direction: column;
    align-items: flex-start;
  }

  .user-avatar {
    margin-bottom: 8px;
  }
}
</style>
